import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_project/add_publish/pic_video_common_utils.dart';
import 'package:flutter_project/common/utils/image_picker_utils.dart';
import 'package:flutter_project/common/utils/screen_size_utils.dart';
import 'package:flutter_project/config/loading_toast.dart';
import 'package:flutter_project/config/theme_color.dart';
import '../common/privacy/dialog_common_view.dart';
import '../common/route_page/route_name.dart';
import '../generated/l10n.dart';
import '../home/home_video_details_model.dart';
import '../home/home_video_details_page.dart';
import '../requst/dio_http_utils.dart';

class PicVideoContentView extends StatefulWidget {
  final VideoDetailsRespModel? itemDetailModel;
  final bool isFromDetail; //是否来自详情页面

  const PicVideoContentView(
      {this.itemDetailModel, this.isFromDetail = false, super.key});

  @override
  State<PicVideoContentView> createState() => _PicVideoContentViewState();
}

class _PicVideoContentViewState extends State<PicVideoContentView> {
  final TextEditingController promptController = TextEditingController();
  final TextEditingController negPromptController = TextEditingController();
  FocusNode promptNode = FocusNode();
  FocusNode negPromptNode = FocusNode();
  final ValueNotifier<int> randomNum = ValueNotifier<int>(0);
  final ValueNotifier<String> rateStr = ValueNotifier<String>('16:9');
  Map rateMap = PicVideoCommonUtils.rateMap();
  List rateKeyList = [];
  List rateValueList = [];
  String textUmodelStr = ''; //文生图模型
  String imgUmodelStr = ''; //图生图模型
  MethodChannel methodChannel = const MethodChannel('initTOSSDK');
  String filePath = '';
  int imgId = 0;
  ValueNotifier<String> imgUrl = ValueNotifier<String>('');

  @override
  Widget build(BuildContext context) {
    double imgWidth = ScreenSizeUtils.deviceScreenWidth(context) - 30;
    double imgHeight = PicVideoCommonUtils.imgHeight;
    return ListView(
      children: [
        const SizedBox(
          height: 10,
        ),
        GestureDetector(
          onTap: () {
            ImagePickerUtils.selectPhotoFromSheet(context, callBackUrl: (res) {
              String imgPath = res ?? '';
              filePath = imgPath;
              if (imgPath.isNotEmpty) {
                PicVideoCommonUtils.requestOTSToken(imgPath,
                    methodChannel: methodChannel);
              }
            });
          },
          child: ValueListenableBuilder(
              valueListenable: imgUrl,
              builder: (BuildContext context, String value, Widget? child) {
                return value.isNotEmpty
                    ? Image.network(
                        value,
                        width: imgWidth,
                        height: imgHeight,
                        fit: BoxFit.cover,
                      )
                    : Container(
                        color: ThemeColor.mainBgColor,
                        width: imgWidth,
                        height: imgHeight,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(
                              Icons.camera_alt_outlined,
                              color: ThemeColor.textColorSecond,
                            ),
                            const SizedBox(
                              height: 10,
                            ),
                            Text(
                              '可上传图片，如不需要，直接输入提示词',
                              style:
                                  TextStyle(color: ThemeColor.hint777777Color),
                            ),
                          ],
                        ),
                      );
              }),
        ),
        PicVideoCommonUtils.getItemView(
            leftName: S.of(context).prompt,
            focusNode: promptNode,
            textEditingController: promptController,
            placeStr: '输入提示词'),
        PicVideoCommonUtils.getItemView(
            leftName: S.of(context).negativePrompt,
            focusNode: negPromptNode,
            textEditingController: negPromptController,
            placeStr: '输入负向提示词'),
        ValueListenableBuilder(
            valueListenable: randomNum,
            builder: (BuildContext context, int value, Widget? child) {
              return PicVideoCommonUtils.getChoseItemView(
                  leftName: S.of(context).seed,
                  rightName: value.toString(),
                  refreshAction: () {
                    getRandomNum();
                  });
            }),
        widget.isFromDetail
            ? SizedBox(
                height: PicVideoCommonUtils.itemHeight,
              )
            : ValueListenableBuilder(
                valueListenable: rateStr,
                builder: (BuildContext context, String value, Widget? child) {
                  return PicVideoCommonUtils.getChoseItemView(
                      leftName: S.of(context).aspectRatio,
                      rightName: value,
                      isHiddenRefresh: true,
                      tapAction: () {
                        cancelKeyBoardResign();
                        PicVideoCommonUtils.getRateBottomView(context,
                            rateKeyList: rateKeyList, tapAction: (res) {
                          rateStr.value = res;
                        });
                      });
                }),
        Container(
          color: Colors.white,
          height: PicVideoCommonUtils.middleHeight(context),
        ),
        PicVideoCommonUtils.deleteViewAndSubmitAction(context, delAction: () {
          cancelKeyBoardResign();
          if (imgUrl.value.isNotEmpty) {
            imgUrl.value = '';
          } else {
            toast('暂无可删除对图片');
          }
        }, submitAction: () {
          submitToGenerateAction();
        }),
      ],
    );
  }

  @override
  void initState() {
    super.initState();
    rateKeyList = rateMap.keys.toList();
    rateValueList = rateMap.values.toList();
    initPlatFormMethod();
    if (widget.itemDetailModel != null) {
      VideoDetailsRespModel detailsRespModel =
          widget.itemDetailModel ?? VideoDetailsRespModel();
      promptController.text = detailsRespModel.prompt ?? '';
      negPromptController.text = detailsRespModel.negativePrompt ?? '';
      randomNum.value = detailsRespModel.seed ?? 0;
      rateStr.value = detailsRespModel.rateStr;
      if (detailsRespModel.imgOriginalUrl.isNotEmpty) {
        imgUrl.value = detailsRespModel.imgOriginalUrl;
        imgId = int.parse(detailsRespModel.fileId);
      }
      setState(() {});
    } else {
      getRandomNum();
    }
    getUnderlyingModels(1);
    getUnderlyingModels(2);
  }

  getRandomNum() {
    randomNum.value = PicVideoCommonUtils.getRandomNum();
  }

  getUnderlyingModels(int type) async {
    var res = await HttpDioUtils.request('model/getAllUnderlyingModels',
        params: {'UmodelType': type});
    if (res != null && res['ErrCode'] == 0) {
      List modelList = res['Resp']['Models'];
      if (modelList.isNotEmpty) {
        if (type == 1) {
          textUmodelStr = modelList.first;
        } else {
          imgUmodelStr = modelList.first;
        }
      }
    }
  }

  //取消键盘响应
  void cancelKeyBoardResign() {
    if (promptNode.hasFocus) {
      promptNode.unfocus();
    }
    if (negPromptNode.hasFocus) {
      negPromptNode.unfocus();
    }
  }

  //生成图片
  submitToGenerateAction() async {
    String promptStr = promptController.text;
    String negativePromptStr = negPromptController.text;
    if (promptStr.isEmpty) {
      toast('请输入提示词');
      return;
    }
    cancelKeyBoardResign();
    String widthHeightStr = rateMap[rateStr.value];
    List widthHeightList = widthHeightStr.split('x');
    int width = int.parse(widthHeightList.first);
    int height = int.parse(widthHeightList.last);
    String imgFileUrl = imgUrl.value;
    List<String> pathList = filePath.split('/');
    Map<String, dynamic> dataMap = {
      'GptPromptist': 0,
      'ToPromptist': 0,
      'Height': height,
      'NegativePrompt': negativePromptStr,
      'Prompt': promptStr,
      'OriginalUmodel': imgFileUrl.isNotEmpty ? imgUmodelStr : textUmodelStr,
      'Seed': randomNum.value,
      'Width': width,
      "AspectRatio": rateStr.value,
    };
    if (imgFileUrl.isNotEmpty) {
      dataMap['ImgUrl'] = imgFileUrl;
      dataMap['Img'] = imgId;
      dataMap['ImgUpload'] = [
        {"name": pathList.last, 'uid': imgId, "url": imgFileUrl}
      ];
      dataMap['OriginalImg'] = imgId;
    }
    debugPrint(dataMap.toString());
    String apiUrl = 'createImgGenerateTask';
    if (imgFileUrl.isNotEmpty) {
      apiUrl = 'createImg2ImgGenerateTask';
    }
    var res = await HttpDioUtils.request('task/$apiUrl', params: dataMap);
    if (res != null && res['ErrCode'] == 0) {
      int imgId = res['Resp']['ImgId'];
      saveSuccess(0, imgId);
    }
  }

  saveSuccess(int type, int fileId) {
    // CommonStringConfig.likeEventBus.fire({"isRefreshHomePage": true});
    ConfirmAlertDialog.showView(context,
        title: '',
        content: '需要等待1～10分钟，结果会在【我的】进行查看，同时可以生成四个作品', rightAction: () {
      RouteNames.pushReplacement(HomeVideoDetailsPage(
        isFromDetails: widget.isFromDetail,
        id: fileId,
        type: type,
      ));
    });
  }

  //从后台拿到图片url
  initPlatFormMethod() {
    const MethodChannel('uploadMedia').setMethodCallHandler((call) async {
      if (call.method == 'upload_media_file') {
        // 处理接收到的消息
        dynamic arguments = call.arguments;
        if (arguments != null) {
          List<String> fileList = filePath.split('/');
          String fileName = fileList.last;
          String path = "platform/png/upload/$fileName";
          Map<String, dynamic> dataMap = {
            "Category": 0,
            "IsShow": true,
            "Path": path,
            "filePath": path,
            "name": fileName,
            "type": 0 //0代表图片  1代表视频
          };
          var res =
              await HttpDioUtils.request('media/uploadMedia', params: dataMap);
          if (res != null && res['ErrCode'] == 0) {
            imgUrl.value = res['Resp']['Img']['Url'];
            imgId = res['Resp']['Img']['Id'];
          }
        }
      }
    });
  }
}
